package com.huixue.cn.ztej.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import sun.misc.BASE64Decoder;
import org.apache.commons.codec.binary.Base64;

import com.huixue.cn.ztej.bean.ConstructionTeam;
import com.huixue.cn.ztej.bean.Examine;
import com.huixue.cn.ztej.bean.Item;
import com.huixue.cn.ztej.bean.Mechanical;
import com.huixue.cn.ztej.bean.MechanicalApply;
import com.huixue.cn.ztej.bean.Results;
import com.huixue.cn.ztej.bean.Section;
import com.huixue.cn.ztej.bean.User;
import com.huixue.cn.ztej.constants.ResourceLocator;
import com.huixue.cn.ztej.constants.UserUtil;
import com.huixue.cn.ztej.enums.RoleStatus;
import com.huixue.cn.ztej.service.SysConstructionTeamService;
import com.huixue.cn.ztej.service.SysMechanicaApplyService;
import com.huixue.cn.ztej.service.SysMechanicaService;
import com.huixue.cn.ztej.service.SysSectionService;
import com.huixue.cn.ztej.service.SysUserService;
import com.huixue.cn.ztej.service.impl.ExamineServiceImpl;
import com.huixue.cn.ztej.utils.MacUtils;
import com.huixue.cn.ztej.utils.Strings;
import com.huixue.cn.ztej.utils.SystemContents.API_RETURN_STATUS;
import com.huixue.cn.ztej.utils.framwork.JacksonUtil;
import com.huixue.cn.ztej.weixin.bean.OAuthInfo;
import com.huixue.cn.ztej.weixin.util.WeixinHelper;


@Controller
@RequestMapping(value = "/mechanicalApply")
//@Scope("prototype")
public class WMechanicalApplyController extends BaseController {

	@Autowired
	SysMechanicaApplyService sysMechanicaApplyService;
	
	@Autowired(required = true)
	SysMechanicaService sysMechanicaService;
	
	@Autowired(required = true)
	SysSectionService sysSectionService;
	
	@Autowired(required = true)
	SysUserService sysUserService;
	
	@Autowired(required = true)
	SysConstructionTeamService sysConstructionTeamService;
	
	@Autowired
	private ExamineServiceImpl examineServiceImpl;
	
	//User currentUser = new User();
	//微信授权认证
	@RequestMapping(value = "/apply")
	public String apply(Model model,HttpServletRequest request) {
		OAuthInfo aouAuthInfo  = WeixinHelper.getUserOpenId(request);
		//通过OpenID获取用户ID--判断审批权限
		User currentUser = sysUserService.findUserByOpenId(aouAuthInfo.getOpenId(),false);
		if(currentUser==null){
			return "/wx/user/noregister";
		}else if(currentUser.getIsAvailable()==UserUtil.DISABLE_YES){
			model.addAttribute("msg", "账号已禁用,请联系管理员");
			return "/wx/message";
		}
		if(currentUser.getRoleId()!=null && 
				Integer.valueOf(currentUser.getRoleId()) == RoleStatus.ROLE_2.getRoleId()){
			
			Results results = sysMechanicaService.listMechanicalType(-1);
			Results constructionteams = sysConstructionTeamService.findAll(Integer.valueOf(currentUser.getProjectID()));
			List<Section> sections = sysSectionService.listSectionByPro(Integer.valueOf(currentUser.getProjectID().trim()));
			List<Item> mechitems = new ArrayList<Item>();
			if(results.getData()!=null){
				List<Mechanical> list = (List<Mechanical>)results.getData();
				if(list!=null && list.size()>0){
					for(int i = 0;i<list.size();i++){
						Mechanical mech = list.get(i);
						Item item = new Item(mech.getMechanicalId()+"",mech.getMechanicalName());
						mechitems.add(item);
					}
				}
			}
			
			List<Item> constructionteamitems = new ArrayList<Item>();
			if(constructionteams.getData()!=null){
				List<ConstructionTeam> list = (List<ConstructionTeam>)(constructionteams.getData());
				if(list!=null && list.size()>0){
					for(int i = 0;i<list.size();i++){
						ConstructionTeam ct = list.get(i);
						Item item = new Item(ct.getTeamId()+"",ct.getName());
						constructionteamitems.add(item);
					}
				}
			}
			
			List<Item> sectionitems = new ArrayList<Item>();
			if(sections!=null && sections.size()>0){
					for(int i = 0;i<sections.size();i++){
						Section st = sections.get(i);
						Item item = new Item(st.getSecId()+"",st.getName());
						sectionitems.add(item);
						if(currentUser.getSegmentID()!=null && Integer.valueOf(currentUser.getSegmentID())==st.getSecId()){
							//model.addAttribute("defalutSection",item);
							model.addAttribute("defalutSecJson",new JacksonUtil().getJson(item));
						}
					}
			}
			
			//得到机械类型json串
			model.addAttribute("mechanicals",new JacksonUtil().getJson(mechitems));
			model.addAttribute("currentUser",currentUser);
			//得到施工队伍json串
			model.addAttribute("constructionteams",new JacksonUtil().getJson(constructionteamitems));
			//得到施工工段json串
			model.addAttribute("sectionitems",new JacksonUtil().getJson(sectionitems));
			
		}else{
			return "/wx/user/noapply";
		}
		
		return "/wx/mechan/mechapply";
	}
	
	@RequestMapping(value="/toSuccess",method=RequestMethod.GET)
	public String success(HttpServletRequest request,Model model){
		model.addAttribute("msg", "申请成功");
		return "/wx/message";
	}
	
	@RequestMapping(value="/toupload",method=RequestMethod.GET)
	public String success1(){
		return "/wx/mechan/MyJsp";
	}
	
	
	@ResponseBody
	@RequestMapping("/common/fileUploadPicture")
	public Object fileUploadPicture(
			@RequestParam(value = "imgdata1", required = false) String imgdata1,
			@RequestParam(value = "imgdata2", required = false) String imgdata2,
			@RequestParam(value = "imgdata3", required = false) String imgdata3,
			HttpServletRequest request) throws IOException {
		BASE64Decoder decoder = new BASE64Decoder();
		FileOutputStream outputStream = null;
		String a = "s";
		try {
			String baseUrl = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/upload/zt143";  
			System.out.println("baseUrl==="+baseUrl);
			String uploadPath = "";
			if(MacUtils.getOSName().startsWith("windows")){
				uploadPath = ResourceLocator.getResourceAbsoluteLocationWin(ResourceLocator.TEMPLATEIMAGE).getAbsolutePath();
			}else{
				uploadPath = ResourceLocator.getResourceAbsoluteLocationLinux(ResourceLocator.TEMPLATEIMAGE).getAbsolutePath();
			}
			File f = new File(uploadPath);
			System.out.println(f.getAbsolutePath());
			//判断父目录路径是否存在，即test.txt前的I:\a\b\
			if (!f.exists()) {    
			    try {
			    	//不存在则创建父目录
			        f.mkdirs();    
			        f.createNewFile();
			    } catch (IOException e) {
			        e.printStackTrace();
			    }
			}
			
			String filePath = uploadPath+ File.separator + Strings.uuid() + ".jpg";
			//String filePath = "/upload/" + Strings.uuid() + ".jpg";
			
			// new一个文件对象用来保存图片，默认保存当前工程根目录
			File filePath1 = new File(filePath);
			// 创建输出流
			outputStream = new FileOutputStream(filePath1);
			// 获得一个图片文件流，我这里是从flex中传过来的
			byte[] result = null;
			if (imgdata1 != null) {
				result = decoder.decodeBuffer(imgdata1.split(",")[1]);// 解码
			} else if (imgdata2 != null) {
				result = decoder.decodeBuffer(imgdata2.split(",")[1]);// 解码
			} else if (imgdata3 != null) {
				result = decoder.decodeBuffer(imgdata3.split(",")[1]);// 解码
			}
			for (int i = 0; i < result.length; ++i) {
				if (result[i] < 0) {// 调整异常数据
					result[i] += 256;
				}
			}
			outputStream.write(result);
			Results results = new Results(API_RETURN_STATUS.NORMAL.value(),
					API_RETURN_STATUS.NORMAL.desc());
			
			
			if(MacUtils.getOSName().startsWith("linux")){
				String[] files = filePath.split("/");
				
				int length = files.length;
				results.setData("/" + files[length - 2] + "/" + files[length - 1]);
				results.setForward(baseUrl+"/" + files[length - 2] + "/" + files[length - 1]);
			}else{
				String[] files = filePath.split("\\\\");
				int length = files.length;
				results.setData("/" + files[length - 3]+"/" + files[length - 2] + "/" + files[length - 1]);
				results.setForward(baseUrl +"/" +files[length - 3]+"/" + files[length - 2] + "/" + files[length - 1]);
			}
			
			return results;
		} catch (Exception e1) {
			e1.printStackTrace();
			logger.error("[文件上传（fileUpload）-fastdfs][errors:" + e1 + "]");
			return new Results(API_RETURN_STATUS.PARA_ERROR.value(),
					API_RETURN_STATUS.PARA_ERROR.desc());
		} finally {
			outputStream.flush();
			outputStream.close();
		}
	} 
	
	/*
	 * @RequestParam(value="frontImage",required=false) MultipartFile frontImage,
			@RequestParam(value="middleImage",required=false) MultipartFile middleImage,
			@RequestParam(value="behindImage",required=false) MultipartFile behindImage,
	 */
	
	@RequestMapping(value = "/save",produces="application/json;charset=UTF-8",method = RequestMethod.POST)
	@ResponseBody
	public Results saveMechanicaApply(@RequestBody MechanicalApply mechanicalApply,
			HttpServletRequest request) {
		mechanicalApply.setApplyTime(new Date());
		//设置工时
		try {
			Date startTime = new SimpleDateFormat("yyyy-MM-dd HH").parse(mechanicalApply.getStartTimeStr());
			
			Date endTime = new SimpleDateFormat("yyyy-MM-dd HH").parse(mechanicalApply.getEndTimeStr());
			
			mechanicalApply.setUseHours((float)(endTime.getTime()-startTime.getTime())/(1000*3600)-mechanicalApply.getDeductHour());

			mechanicalApply.setStartTime(startTime);
			mechanicalApply.setEndTime(endTime);
			
			String ctx = request.getContextPath();
		
			
			String t = ctx.replace("/", "\\");
			if(mechanicalApply.getFrontImage().startsWith(t)){
				//mechanicalApply.setFrontImage( mechanicalApply.getFrontImage().replace(ctx, ""));
				mechanicalApply.setFrontImage( mechanicalApply.getFrontImage().replace(t, ""));
			}
			
			if(mechanicalApply.getMiddleImage().startsWith(t)){
				//mechanicalApply.setMiddleImage( mechanicalApply.getMiddleImage().replace(ctx, ""));
				mechanicalApply.setMiddleImage(mechanicalApply.getMiddleImage().replace(t, ""));
			}
			
			if(mechanicalApply.getBehindImage().startsWith(t)){
				//mechanicalApply.setBehindImage( mechanicalApply.getBehindImage().replace(ctx, ""));
				mechanicalApply.setBehindImage(mechanicalApply.getBehindImage().replace(t, ""));
			}
			
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		//设置总费用
		if(mechanicalApply.getRent()==1){
			mechanicalApply.setFee(mechanicalApply.getPrice()*mechanicalApply.getQuantity()*mechanicalApply.getUseHours());
		}else if(mechanicalApply.getRent()==2){
			mechanicalApply.setFee(mechanicalApply.getPrice()*mechanicalApply.getQuantity()*mechanicalApply.getUseHours()*(-1));
		}
		
		//设置状态
		mechanicalApply.setState(0);
		//设置申请时间
		mechanicalApply.setApplyTime(new Date());
		mechanicalApply.setCreateTime(new Date());
		mechanicalApply.setMechanicalId(Integer.valueOf(mechanicalApply.getMechanicalModel()));
		//User currentUser = sysUserService.findUserById(mechanicalApply.getApplyUserId());
		//设置工段
		//mechanicalApply.setApplyUserId(currentUser.getUser_id());
		/*if(mechanicalApply.getSegmentId() == null){
			mechanicalApply.setSegmentId(Integer.valueOf(currentUser.getSegmentID()));
		}
		mechanicalApply.setProId(Integer.valueOf(currentUser.getProjectID()));	*/
		
		String errorCode="";
		try {
			
            Results res = sysMechanicaApplyService.saveMechanicaApply(mechanicalApply);
            return res;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new Results(API_RETURN_STATUS.PIC_FORMAT_ERROR.value(),
				API_RETURN_STATUS.PIC_FORMAT_ERROR.desc(),"保存失败！");
	}
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH"), true));
	}
	
	/** 
	 * 查找机械申请
	 * @param applyId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/view/{applyId}/{userId}")
	public String view(@PathVariable("applyId")Integer applyId,@PathVariable("userId")Integer userId,HttpServletRequest request,Model model) {	   
		
		User  currentUser = null;
		
	    if(request.getSession().getAttribute("currentUser")!=null){
	    	model.addAttribute("user", request.getSession().getAttribute("currentUser"));
	    }else{
	    	currentUser = sysUserService.findUserById(Integer.valueOf(325));
	    	model.addAttribute("user", currentUser);
	    }
	    
	    //查看机械申请
		MechanicalApply apply = sysMechanicaApplyService.findById(Integer.valueOf(applyId));
		model.addAttribute("res", apply);
		
		//查看审批详情
		List<Examine> examineList = examineServiceImpl.selectByApplyId(apply.getApplyId(),2);
		model.addAttribute("examineList", examineList);
		
		Map<String,Object> searchParams = new HashMap<String,Object>();
		searchParams.put("projectID", apply.getProId()+"");
		//查找下级审批
		/*if(apply.getState()==0){
			searchParams.put("roleId", RoleStatus.ROLE_3.getRoleId()+"");
		}else if(apply.getState()==3){
			searchParams.put("segmentID", apply.getSegmentId()+"");
			searchParams.put("roleId", RoleStatus.ROLE_4.getRoleId()+"");
		}else if(apply.getState()==4){
			searchParams.put("roleId", RoleStatus.ROLE_5.getRoleId()+"");
		}else if(apply.getState()==5){
			searchParams.put("roleId", RoleStatus.ROLE_6.getRoleId()+"");
		}*/
		
		if(apply.getState()==0){
			searchParams.put("segmentID", apply.getSegmentId()+"");
			searchParams.put("roleId", RoleStatus.ROLE_4.getRoleId()+"");
		}else if(apply.getState()==4){
			searchParams.put("roleId", RoleStatus.ROLE_3.getRoleId()+"");
		}else if(apply.getState()==3){
			searchParams.put("roleId", RoleStatus.ROLE_5.getRoleId()+"");
		}else if(apply.getState()==5){
			searchParams.put("roleId", RoleStatus.ROLE_6.getRoleId()+"");
		}
		
		User nextApprovUser = sysUserService.findUserByParams(searchParams);
		//System.out.println("==nextApprovUser=="+nextApprovUser.getUserName());
		model.addAttribute("nextApprovUser", nextApprovUser);
		
		return "/wx/approve/mechianView";
	}
	
	
	@RequestMapping(value = "/listMechanicalByType",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	@ResponseBody 
	public String listMechanicalByType(@RequestBody Mechanical mechanical,HttpServletRequest request,HttpServletResponse response) {
		
		Results results =sysMechanicaService.listMechanicalType(mechanical.getMechanicalId());
		
		List<Item> mechitems = new ArrayList<Item>();
		if(results.getData()!=null){
			List<Mechanical> list = (List<Mechanical>)results.getData();
			if(list!=null && list.size()>0){
				for(int i = 0;i<list.size();i++){
					Mechanical mech = list.get(i);
					Item item = new Item(mech.getMechanicalId()+"",mech.getMechanicalModel());
					mechitems.add(item);
				}
			}
		}
		
		Results items = new Results(API_RETURN_STATUS.NORMAL.value(),API_RETURN_STATUS.NORMAL.desc(),mechitems);
		return new JacksonUtil().getJson(items);
	}
	
	
}
